//
//  MWShowroomGoodsController.m
//  XiRan-iOS
//
//  Created by liuyiming on 2019/12/4.
//  Copyright © 2019 Wood. All rights reserved.
//

#import "MWShowroomGoodsController.h"

#import "MWGoodsDetailsController.h"
#import "MWHomeSearchController.h"

#import "MWGoodsCell.h"

#import "MWFilterMenuView.h"
#import "MWFilterDropMenuView.h"

#import "MWFilterModel.h"

@interface MWShowroomGoodsController () <UICollectionViewDataSource, UICollectionViewDelegate, MWFilterDropMenuViewDelegate>

@property(nonatomic, strong) UIView *menuView;
@property(nonatomic, strong) UIView *deviderLineView;
@property(nonatomic, strong) UIButton *filterBtn;

@property(nonatomic, strong) UICollectionView *collectionView;

@property(strong, nonatomic) MWFilterDropMenuView *dropMenuView;
@property(strong, nonatomic) MWFilterMenuView *filterView;

@property(nonatomic, strong) NSMutableArray *filterBtnArray;     // 筛选按钮

@property(nonatomic, strong) NSString *searchStr;

@property(strong, nonatomic) NSMutableArray *categoryFilterArray;
@property(strong, nonatomic) NSMutableArray *filterArray;
@property(strong, nonatomic) NSMutableArray *goodsArray;

@property(nonatomic, assign) CGFloat cellHeight;

@property(nonatomic, assign) NSInteger page;
@property(nonatomic, assign) NSInteger size;
@property(nonatomic, assign) MWRequestMode requestMode;

@property (nonatomic, assign) BOOL isShaixuan;

@end

@implementation MWShowroomGoodsController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = [[MWConfigManager manager] objectForKey:@"goods" defaultValue:@"商品"];
    
    [self setupPageSubviews];
    [self layoutPageSubviews];
    
    _page = 1;
    _size = 10;
    _searchStr = @"";
    
    [self loadFilter];
    [_collectionView.mj_header beginRefreshing];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (_dropMenuView.isShow) {
        [_dropMenuView dismiss];
    }
}

-(void)searchAvtion:(UIButton *)sender {
    MWHomeSearchController *controller = [[MWHomeSearchController alloc] init];
    controller.showroom = self.showroom;
    [self.navigationController pushViewController:controller animated:YES];
}

- (void)configFilterMenu {
    _filterBtnArray = [[NSMutableArray alloc] init];
    
    NSInteger count = self.categoryFilterArray.count;
    CGFloat width = (kScreenWidth - 70) / count;
    
    for (int i = 0; i < count; i++) {
        MWFilterModel *filter = self.categoryFilterArray[i];
        UIButton *menuBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        menuBtn.frame = CGRectMake(width * i + 10, 0, width, 44);
        menuBtn.tag = i;
        menuBtn.titleLabel.font = MWFont(12);
        [menuBtn setTitle:filter.attr_name forState:UIControlStateNormal];
        [menuBtn setTitleColor:MWHexColor(@"#333333") forState:UIControlStateNormal];
        [menuBtn setTitleColor:MWHexColor(@"#FD9F2B") forState:UIControlStateSelected];
        [menuBtn setImage:[UIImage imageNamed:@"ic_drop_down_n"] forState:UIControlStateNormal];
        [menuBtn setImage:[UIImage imageNamed:@"ic_drop_down_s"] forState:UIControlStateSelected];
        [menuBtn addTarget:self action:@selector(onClickAction:) forControlEvents:UIControlEventTouchUpInside];
        [menuBtn setIconInRightWithSpacing:2];
        [_menuView addSubview:menuBtn];
        [_filterBtnArray addObject:menuBtn];
    }
}

#pragma mark - 目录筛选条件 和 更多筛选条件
- (void)loadFilter {
    [self loadCatalogFilter];
    [self loadMoreFilter];
}

#pragma mark - 商品目录筛选条件
- (void)loadCatalogFilter {
    NSString *token = [MWUserManager manager].user.token;
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:token forKey:@"token"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];
    [paraDic setObject:[MWConfigManager manager].productType forKey:@"is_material"];
    [[MWNetworkManager manager] POST:kGoodsFilterUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSArray *tempArray = [MWFilterModel mj_objectArrayWithKeyValuesArray:[dic objectForKey:@"data"]];
        [self.categoryFilterArray addObjectsFromArray:tempArray];
        NSMutableArray *mpArray = [NSMutableArray arrayWithCapacity:4];
        for (MWFilterModel *model1 in self.categoryFilterArray) {
            for (MWFilterModel *model2 in self.filterArray) {
                if (model1.mid == model2.mid) {
                    [mpArray addObject:model2];
                }
            }
        }
        
        [self.categoryFilterArray removeAllObjects];
        [self.categoryFilterArray addObjectsFromArray:tempArray];
        
        [self configFilterMenu];

        
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark - 更多筛选条件
- (void)loadMoreFilter {
    NSString *token = [MWUserManager manager].user.token;
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:token forKey:@"token"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];
    [paraDic setObject:[MWConfigManager manager].productType forKey:@"is_material"];
    [[MWNetworkManager manager] POST:kFilterUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSArray *tempArray = [MWFilterModel mj_objectArrayWithKeyValuesArray:[dic objectForKey:@"data"]];
        [self.filterArray addObjectsFromArray:tempArray];
                
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark - 商品列表
- (void)refreshGoods {
    _page = 1;
    _requestMode = MWRequestModeRefresh;
    [self loadGoodsWithSearch:_searchStr page:_page size:_size];
}

- (void)loadMoreGoods {
    _page++;
    _requestMode = MWRequestModeLoadMore;
    [self loadGoodsWithSearch:_searchStr page:_page size:_size];
}

- (void)loadGoodsWithSearch:(NSString *)search page:(NSInteger)page size:(NSInteger)size {
    NSString *token = [MWUserManager manager].user.token;
    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
    [paraDic setObject:token forKey:@"token"];
    [paraDic setObject:_showroom forKey:@"gallery"];
    [paraDic setObject:search forKey:@"search"];
    [paraDic setObject:[NSString stringWithFormat:@"%ld", page] forKey:@"page"];
    [paraDic setObject:[NSString stringWithFormat:@"%ld", size] forKey:@"size"];
    [paraDic setObject:[MWConfigManager manager].language forKey:@"language"];
    [paraDic setObject:[MWConfigManager manager].productType forKey:@"is_material"];

    MWWeakSelf
    [[MWNetworkManager manager] POST:kShowroomGoodsUrl parameters:paraDic progress:^(NSProgress *downloadProgress) {
        
    } success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        NSInteger code = [[dic objectForKey:@"code"] integerValue];
//        NSString *msg = [dic objectForKey:@"msg"];
        if (code == 1) {
            NSArray *tempArray = [MWGoods mj_objectArrayWithKeyValuesArray:[dic objectForKey:@"data"]];
            if (weakSelf.requestMode == MWRequestModeRefresh) {
                [weakSelf.collectionView.mj_header endRefreshing];
                [weakSelf.goodsArray removeAllObjects];
            } else {
                if (tempArray.count < weakSelf.size) {
                    [weakSelf.collectionView.mj_footer endRefreshing];
                } else {
                    [weakSelf.collectionView.mj_footer endRefreshing];
                }
            }
            
            [weakSelf.goodsArray addObjectsFromArray:tempArray];
            weakSelf.cellHeight = [self calculateCellHeight];
            [weakSelf.collectionView reloadData];
            
        } else {
            [weakSelf.collectionView.mj_header endRefreshing];
            [weakSelf.collectionView.mj_footer endRefreshing];
        }
        
    } failure:^(NSError *error) {
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
    }];
}

- (void)updateGoodsList {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (self.isShaixuan) {
        for (MWFilterModel *model in self.filterArray) {
            NSString *ids = @"";
            for (MWAttribute *attr in model.attr_list) {
                if (attr.isSelected) {
                    ids = [NSString stringWithFormat:@"%@,%ld", ids, attr.mid];
                }
            }
            if (ids.length > 0) {
                ids = [ids substringFromIndex:1];
                [dic setObject:ids forKey:[NSString stringWithFormat:@"%ld", model.mid]];
            }
        }
    } else {
        for (MWFilterModel *model in self.categoryFilterArray) {
            NSString *ids = @"";
            for (MWAttribute *attr in model.attr_list) {
                if (attr.isSelected) {
                    ids = [NSString stringWithFormat:@"%@,%ld", ids, attr.mid];
                }
            }
            if (ids.length > 0) {
                ids = [ids substringFromIndex:1];
                [dic setObject:ids forKey:[NSString stringWithFormat:@"%ld", model.mid]];
            }
        }
    }
    if (dic.count == 0) {
        _searchStr = @"";
    } else {
        _searchStr = [NSString convertJSONWithDic:dic];
    }
    [_collectionView.mj_header beginRefreshing];
}

#pragma mark - 筛选事件
- (void)onClickAction:(UIButton *)sender {
    if (sender.tag == 1000) {
        self.isShaixuan = YES;
        MWWeakSelf
        if (_dropMenuView.isShow) {
            [_dropMenuView close];
        }
        
        if (!_filterView) {
            _filterView = [[MWFilterMenuView alloc] init];
        }
        [_filterView setContentArray:self.filterArray];
        _filterView.selectBlock = ^() {
            [weakSelf updateGoodsList];
        };
        
        _filterView.resetBlock = ^{
            weakSelf.searchStr = @"";
            [weakSelf.collectionView.mj_header beginRefreshing];
        };
        
        [_filterView show];
    
    } else {
        self.isShaixuan = NO;
        if (!_dropMenuView) {
             _dropMenuView = [[MWFilterDropMenuView alloc] init];
            _dropMenuView.delegate = self;
        }
       
        if (_dropMenuView.isShow) {
            [_dropMenuView close];
            
        } else {
            sender.selected = YES;
            [_dropMenuView configFilterTitles:_categoryFilterArray[sender.tag]];
            [_dropMenuView show];
        }
    }
}

#pragma mark - MWTextureViewDelegate
- (void)filterDropMenuViewDismiss {
    for (UIButton *filterBtn in self.filterBtnArray) {
        filterBtn.selected = NO;
    }
}

- (void)filterDropMenuViewReset {
    _searchStr = @"";
    [_collectionView.mj_header beginRefreshing];
}

- (void)filterDropMenuViewEnsure {
    [self updateGoodsList];
}

#pragma mark - UICollectionViewDataSource && UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if ([MWConfigManager manager].isNetError) {
        self.errorTitleLabel.text = [[MWConfigManager manager] objectForKey:@"click_retry" defaultValue:@"点击重试"];
        self.errorTitleLabel.hidden = self.errorImageView.hidden = NO;
        collectionView.hidden = YES;
        self.menuView.hidden = YES;
    } else if (!self.goodsArray.count) {
        if (self.isFirst) {
            
        } else {
            self.errorTitleLabel.text = [[MWConfigManager manager] objectForKey:@"nodata" defaultValue:@"暂无数据"];
            self.errorTitleLabel.hidden = self.errorImageView.hidden = NO;
            collectionView.hidden = YES;
            self.menuView.hidden = NO;
        }
    } else {
        self.errorTitleLabel.hidden = self.errorImageView.hidden = YES;
        collectionView.hidden = NO;
        self.menuView.hidden = NO;
    }
    return self.goodsArray.count;
}

- (void)refresh {
    [super refresh];
    [self loadFilter];
    [self.collectionView.mj_header beginRefreshing];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"MWGoodsCell";
    MWGoodsCell *goodCell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    [goodCell setupData:self.goodsArray[indexPath.row]];
    return goodCell;
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 12;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 20;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(16, 16, 16, 16);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((kScreenWidth - 52) / 2, _cellHeight);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    MWGoods *goods = self.goodsArray[indexPath.row];
    MWGoodsDetailsController *controller = [[MWGoodsDetailsController alloc] init];
    controller.productId = [NSString stringWithFormat:@"%ld", goods.mid];
    [self.navigationController pushViewController:controller animated:YES];
}

#pragma mark - 计算cell 高度
- (CGFloat)calculateCellHeight {
    CGFloat imgH = 120.0f;
    CGFloat titleH = 22.0f;
    CGFloat priceH = 0;
    CGFloat attrH = 0.0f;
    
    for (MWGoods *goods in self.goodsArray) {
        if (!goods.shuxing) {
            break;
        }
        
        if (goods.price) {
            priceH = 22.0f;
        }
        
        if (attrH < goods.shuxing.count * 22) {
            attrH = goods.shuxing.count * 22;
        }
    }
    
    return imgH + 8 + titleH + priceH + attrH;
}


- (NSMutableArray *)categoryFilterArray {
    if (!_categoryFilterArray) {
        _categoryFilterArray = [[NSMutableArray alloc] init];
    }
    return _categoryFilterArray;
}

- (NSMutableArray *)filterArray {
    if (!_filterArray) {
        _filterArray = [[NSMutableArray alloc] init];
    }
    return _filterArray;
}

- (NSMutableArray *)goodsArray {
    if (!_goodsArray) {
        _goodsArray = [[NSMutableArray alloc] init];
    }
    return _goodsArray;
}

- (void)setupPageSubviews {
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = CGRectMake(0, 0, 20, 20);
    [searchBtn setImage:[UIImage imageNamed:@"ic_search_white"] forState:UIControlStateNormal];
    [searchBtn setImage:[UIImage imageNamed:@"ic_search_white"] forState:UIControlStateHighlighted];
    [searchBtn addTarget:self action:@selector(searchAvtion:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithCustomView:searchBtn];
    self.navigationItem.rightBarButtonItem = buttonItem;
    
    _menuView = [[UIView alloc] init];
    _menuView.backgroundColor  = MWHexColor(@"#F6F7FB");
    [self.view addSubview:_menuView];
    
    _deviderLineView = [[UIView alloc] init];
    _deviderLineView.backgroundColor = MWHexColor(@"#979797");
    [_menuView addSubview:_deviderLineView];
       
    _filterBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _filterBtn.tag = 1000;
    _filterBtn.titleLabel.font = MWFont(12);
    [_filterBtn setTitle:[[MWConfigManager manager] objectForKey:@"shuaixuan" defaultValue:@"筛选"] forState:UIControlStateNormal];
    [_filterBtn setTitleColor:MWHexColor(@"#333333") forState:UIControlStateNormal];
    [_filterBtn setTitleColor:MWHexColor(@"#FD9F2B") forState:UIControlStateSelected];
    [_filterBtn setImage:[UIImage imageNamed:@"ic_filter"] forState:UIControlStateNormal];
    [_filterBtn setImage:[UIImage imageNamed:@"ic_filter"] forState:UIControlStateSelected];
    [_filterBtn addTarget:self action:@selector(onClickAction:) forControlEvents:UIControlEventTouchUpInside];
    [_menuView addSubview:_filterBtn];

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
     [_collectionView registerClass:[MWGoodsCell class] forCellWithReuseIdentifier:@"MWGoodsCell"];
    [self.view addSubview:_collectionView];
    
    MJRefreshNormalHeader *refreshHeader = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self refreshGoods];
    }];
    refreshHeader.stateLabel.hidden = YES;
    _collectionView.mj_header = refreshHeader;
    
    MJRefreshBackNormalFooter *refreshFooter = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreGoods];
    }];
    refreshFooter.stateLabel.hidden = YES;
    _collectionView.mj_footer.hidden = YES;
    _collectionView.mj_footer = refreshFooter;
}

- (void)layoutPageSubviews {
    [_menuView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.equalTo(@44);
    }];

    [_filterBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.menuView).offset(-10);
        make.width.equalTo(@50);
        make.height.equalTo(self.menuView);
    }];
    [_filterBtn setIconInRightWithSpacing:5];
    
    [_deviderLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.filterBtn.mas_left).offset(-0.5);
        make.centerY.equalTo(self.menuView);
        make.width.equalTo(@0.5);
        make.height.equalTo(@15);
    }];
    
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.menuView.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
}


@end
